import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:proj_sfv/component/LoadingOverlay.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:image_picker/image_picker.dart';
import 'package:proj_sfv/utils/Utils.dart';
import 'package:mime_type/mime_type.dart';


enum Gender { MALE, FAMALE }

class RegisterPage extends StatefulWidget {
  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final _formKey = GlobalKey<FormState>();

  String _name;
  String _email;
  String _password;
  String _passwordFirm;
  File _currentFile = null;
  Gender _gender;
  ImageProvider _currentProfile = AssetImage("assets/owl.jpg");
  bool _loading = false;
  final _picker = ImagePicker();

  void _pickProfile() async {
    XFile image = await _picker.pickImage(source: ImageSource.gallery);
    setState(() {
      if (image != null) {
        _currentFile = File(image.path);
        _currentProfile = FileImage(_currentFile);
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('用户注册'),
        ),
        body: LoadingOverlay(
          isLoading: _loading,
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Expanded(
                  child: Column(
                    children: [
                      Expanded(
                        child: Row(
                          children: [
                            CircleAvatar(
                              backgroundImage: _currentProfile,
                              radius: 60,
                            ),
                            TextButton(onPressed: () => _pickProfile(), child: Text("选择头像"))
                          ],
                        ),
                      ),
                      Column(
                        children: [
                          TextFormField(
                            decoration: InputDecoration(labelText: '用户名'),
                            validator: (value) {
                              if (value.isEmpty) {
                                return '请输入用户名';
                              }
                              return null;
                            },
                            onSaved: (value) {
                              _name = value;
                            },
                          ),
                          TextFormField(
                            decoration: InputDecoration(labelText: '邮箱'),
                            validator: (value) {
                              return null;
                            },
                            onSaved: (value) {
                              _email = value;
                            },
                          ),
                          TextFormField(
                            decoration: InputDecoration(labelText: '密码'),
                            obscureText: true,
                            validator: (value) {
                              if (value.isEmpty) {
                                return '请输入密码';
                              }
                              return null;
                            },
                            onSaved: (value) {
                              _password = value;
                            },
                          ),
                          TextFormField(
                            decoration: InputDecoration(labelText: '验证密码'),
                            obscureText: true,
                            validator: (value) {
                              if (value.isEmpty) {
                                return '请再次输入密码';
                              } else if (_password != _passwordFirm) {
                                return '两次输入不一致';
                              }
                              return null;
                            },
                            onSaved: (value) {
                              _passwordFirm = value;
                            },
                          ),
                          FormField(
                            builder: (field) {
                              return Row(
                                children: [
                                  Row(
                                    children: [
                                      Radio<Gender>(
                                        groupValue: _gender,
                                        value: Gender.MALE,
                                        onChanged: (Gender value) {
                                          setState(() {
                                            _gender = value;
                                          });
                                        },
                                      ),
                                      Text("男")
                                    ]
                                  ),
                                  Row(
                                    children: [
                                      Radio<Gender> (
                                        groupValue: _gender,
                                        value: Gender.FAMALE,
                                        onChanged: (Gender value) {
                                          setState(() {
                                            _gender = value;
                                          });
                                        },
                                      ),
                                      Text("女")
                                    ]
                                  )
                              ]
                              );
                            },
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Padding(
                    padding: const EdgeInsets.symmetric(vertical: 16.0),
                    child: Center(
                      child: ElevatedButton(
                        child: Text("注册"),
                        onPressed: () => tryRegister(),
                        // onPressed: () {
                        //   if (_formKey.currentState.validate()) {
                        //     _formKey.currentState.save();
                        //   }
                      ),
                    )
                )
              ]
            )
          ),
        )
    );
  }

  void tryRegister() async {
      if (_formKey.currentState.validate()) {
        _formKey.currentState.save();
      } else {
        return;
      }
      setState(() {
        _loading = true;
      });
      String base64;
      if (_currentFile == null) {
        base64 = await getImageBase64("assets/owl.jpg", "image/jpg");
      } else {
        String mimeType = mime(_currentFile.path);
        String data = Base64Encoder().convert(_currentFile.readAsBytesSync());
        base64 = 'data:$mimeType;base64,$data';
      }
      bool gender = _gender == Gender.FAMALE ? false : true;
      var value = await registerRequest(context, base64, _name, _email, _password, gender);
      if (value != null) {
        Fluttertoast.showToast(msg: "注册成功,id为:${value['id']}");
        setState(() {
          _loading = false;
        });
      Navigator.pop(context, <String, String>{
          "id": value['id'],
          "token": value['token'],
          "sig": value['sig'],
          "gender": value['gender'],
          "profile": value['profile'],
          "userName": value['userName'],
          "birthday": value['birthday']
        });
      }
      else {
        setState(() {
          _loading = false;
        });
      }
  }

}